<?php

namespace System\Configure\Adapter;

use System\Configure\AdapterAbstract;
use System\Configure\Exception\ParserIniException;

/**
 *
 * @author Administrator
 */
class Ini extends AdapterAbstract
{

    /**
     * 解析INI配置文件到数组
     *
     * @access public
     * @param string $path 配置文件路径
     * @return array 返回配置项数组
     * @throws ParseException 解析INI配置文件到数组异常
     */
    public function parser($path)
    {
        $ini = @parse_ini_file($path, true);
        $data = [];
        foreach ($ini as $namespace => $properties) {
            list ($name, $extends) = explode(':', $namespace);
            $name = trim($name);
            $extends = trim($extends);
            // create namespace if necessary
            if (! isset($data[$name])) {
                $data[$name] = array();
            }
            // inherit base namespace
            if (isset($ini[$extends])) {
                foreach ($ini[$extends] as $prop => $val)
                    $data[$name][$prop] = $val;
            }
            // overwrite / set current namespace values
            foreach ($properties as $prop => $val)
                $data[$name][$prop] = $val;
        }
        if (! $data) {
            $error = error_get_last();
            throw new ParserIniException([
                [
                    'system.conf.parser.toarray.error'
                ],
                [
                    'error' => $error
                ]
            ]);
        }
        return $data;
    }
}